package com.museum.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(WebConfig.class);

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 确保上传目录存在
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        
        // 获取绝对路径
        String absolutePath = dir.getAbsolutePath();
        
        // 确保路径以文件分隔符结尾
        if (!absolutePath.endsWith(File.separator)) {
            absolutePath += File.separator;
        }
        
        // 记录静态资源映射信息
        logger.info("Mapping /uploads/** to file:{}", absolutePath);
        
        // 设置不同的上传文件访问路径映射
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:" + absolutePath);
                
        // 为了兼容API路径访问，添加一个带API路径前缀的映射
        registry.addResourceHandler("/api/uploads/**")
                .addResourceLocations("file:" + absolutePath);
                
        // 添加静态资源文件夹映射
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
                
        // 添加测试页面映射
        registry.addResourceHandler("/test-images")
                .addResourceLocations("classpath:/static/test.html");
    }
} 